<template>
  <!-- 车主数据》车辆颜色 -->
  <div>
    <TopFilter
      :list="topFilterList"
      :cols="4"
      @filterChange="changeHandle"
      @onCollapse="collapseHandle"
    ></TopFilter>
    <div id="Chartdiv" style="margin:10px 0;background:#F2F4F8;display:flex;justify-content: space-between;">
      <div class="Chartf">
        <div class="ChartTop">
          潜客意向级别分布
        </div>
        <Chart1 :option="option1" :containerStyle="{height: '300px'}"/>
      </div>
      <div class="Chartf">
        <div class="ChartTop">
          意向车系分布
        </div>
        <Chart1 :option="option2" :containerStyle="{height: '300px'}"/>
      </div>
    </div>
    <div>
        <div class="maintop">
          <el-tabs class="lazyLoadTab" v-model="activeName" @tab-click="handleClick">
            <el-tab-pane class="lazyLoadTabPane" label="数值" name="first"></el-tab-pane>
            <el-tab-pane class="lazyLoadTabPane" label="占比" name="second"></el-tab-pane>
          </el-tabs>
          <div class="maintopleft">
            <el-radio-group v-model="radio1" @change="changeClue">
              <el-radio-button
                v-for="(item, index) in radioList"
                :key="index"
                :label="item.value"
              >{{item.text}}</el-radio-button>
            </el-radio-group>
          </div>
          <!-- <LazyLoadTab v-model="activeName" :tabMenus="menus"></LazyLoadTab> -->
        </div>

        <div class="tabShow">
          <potenCusModal v-if="activeName === 'first'" :rowDate="formData" :columns="columns" :dataSource="dataSource"/>
          <potenCusModal v-if="activeName === 'second'" :rowDate="formData" :columns="columns" :dataSource="dataSource"/>
        </div>
    </div>


  </div>
</template>

<script>
import {
  queryNewPotentialCount,
  getEmployeeInfo
 } from '@/api/report/retail/potenCusInsertStat';
import { getOrgTeam, getUserByOrgId } from '@/api/report/retail/clueFunnelAnalysis';
import { dictionary } from '@/utils/dictMixin';
import Chart1 from '@/charts/preSale/chart1';
import { authority } from '@/utils/authMixin';
import { arrayObjDeWeight, integration, integrations, GetPercent, computedAll, getTextByJs } from '@/utils/index';
import { ObjectAssign, sortRule } from '@/components/DataMerge';
import potenCusModal from './potenCusModal';
import moment from 'moment';
export default {
  name: 'potenCusInsertStat',
  mixins: [dictionary,authority],
  components: {
    Chart1,
    potenCusModal
  },
  data() {
    return {
      columns:[],
      dataSource: [],
      initDataSource: [],
      topFilterList: this.createTopFilters(),
      fetchParams: {
        startDate:moment().format("YYYY-MM-DD"),
        endDate:moment().format("YYYY-MM-DD")
      },
      visible: false,
      dialogTitle: '',
      handleType: '',
      formData: {},
      conf:{ add: '新增', edit: '编辑', show: '显示' },
      option1: {},
      option2: this.createOption2(),
      radio1: 'clueIdLevelOne',
      radioList: [{ value: 'clueIdLevelOne', text: '一级来源' }, { value: 'clueIdLevelTwo', text: '二级来源' }, { value: 'clueIdLevelThree', text: '三级来源' }, { value: 'clueIdLevelFour', text: '四级来源' }],
      activeName: 'first',
      menus: [
        {
          title: '数值',
          path: 'report/retail/potenCusInsertStat/potenCusModal',
          params: { type: 'numerical' , rowData: this.formData }
        },
        {
          title: '占比',
          path: 'report/retail/potenCusInsertStat/potenCusModal',
          params: { type: 'proportion' , rowData: this.formData }
        },
      ]
    };
  },
  methods: {
    createTopFilters() {
      return [
        {
          type: 'SELECT',
          label: '日期维度',
          fieldName: 'dateType',
          placeholder: '请选择',
          initialValue: 'day',
          itemList: [
            { value: 'day', text: '日' },
            { value: 'week', text: '周' },
            { value: 'month', text: '月' },
            { value: 'quarter', text: '季' },
            { value: 'year', text: '年' },
            { value: 'date', text: '期间' }
          ],
          change: val => {
            this.changeTemplateType(val);
          }
        },
        {
          type: 'DATE',
          label: '日期',
          fieldName: 'datetime',
          placeholder: '',
          dateType: 'exactdate',
          initialValue: moment().format("YYYY-MM-DD"),
          change: (val, fieldName) => {
            // console.log(val,fieldName)
            this.quarterTime = val;
          }
        },
        {
          type: 'SELECT',
          label: '销售小组',
          fieldName: 'orgId',
          placeholder: '请选择...',
          itemList: [],
          change: val => {
            // console.log(val,fieldName)
            this.getUserByOrgId(val);
          }
        },
        {
          type: 'MULTIPLE_SELECT',
          label: '销售顾问',
          fieldName: 'consultants',
          placeholder: '请选择...',
          itemList: []
        }
      ];
    },
    createOption1(){
      return {
        tooltip: {
          trigger: 'item',
          formatter: "{b} <br/>数量: {c} ({d}%)",
          backgroundColor: 'rgba(0,0,0,0.75)',
        },
        legend: {
          icon: 'circle',
          itemWidth: 8,
          itemHeight: 8,
          textStyle: {
            color: 'rgba(0,4,10,0.45)'
          },
          type: 'scroll',
          orient: 'vertical',
          right: 10,
          top: '30%',
          formatter: '{name}',
        },
        series: [
            {
              // name:'意向级别',
              type:'pie',
              center: ['40%', '50%'],
              radius: ['40%', '70%'],
              avoidLabelOverlap: false,
              label: {
                normal: {
                  show: false,
                  position: 'center'
                },
                emphasis: {
                  show: false,
                  textStyle: {
                    fontSize: '30',
                    fontWeight: 'bold'
                  }
                }
              },
              labelLine: {
                normal: {
                  show: false
                }
              },
              data:[]
            }
        ],
        color:['#FF4D4F', '#FF956B', '#FFD164', '#5FD9D4', '#C8EB5F'],
      }
    },
    createOption2(){
      return {
        tooltip: {
          trigger: 'item',
          formatter: "{a} <br/>{b}: {c} ({d}%)",
          backgroundColor: 'rgba(0,0,0,0.75)',
        },
        legend: {
          icon: 'circle',
          itemWidth: 8,
          itemHeight: 8,
          textStyle: {
            color: 'rgba(0,4,10,0.45)'
          },
          type: 'scroll',
          orient: 'vertical',
          right: 10,
          top: '30%',
          formatter: '{name}',
          // data:[{intentLevel:'A',proportion:20},{intentLevel:'B',proportion:20},{intentLevel:'C',proportion:20},{intentLevel:'H',proportion:20},{intentLevel:'O',proportion:20}]
        },
        series: [
          {
            // name:'意向车系',
            type:'pie',
            center: ['40%', '50%'],
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            label: {
              normal: {
                show: false,
                position: 'center'
              },
              emphasis: {
                show: false,
                textStyle: {
                  fontSize: '30',
                  fontWeight: 'bold'
                }
              }
            },
            labelLine: {
              normal: {
                show: false
              }
            },
            data:[]
          }
        ],
        color:['#FFD164', '#6940E9', '#C8EB5F', '#5FD9D4', '#7B98F9', '#FF956B'],
      }
    },

    async queryNewPotentialCount() {
      const res = await queryNewPotentialCount(this.fetchParams);
      // console.log('销售顾问', res)
      if (res.resultCode === 200) {
        let arr = [],arr2 = [],option1 = this.createOption1(),option2 = this.createOption2();
        res.data.intentVO.map(x=>{
          arr.push({
            name:this.createDictText(x.intentLevel, '1519'),
            value:x.total
          })
        })
        option1.series[0].data = arr;
        res.data.seriesVO.map(x=>{
          arr2.push({
            name:x.intentSeriesName || x.intentSeriesId || '未知',
            value:x.total
          })
        })
        option2.series[0].data = arr2;

        this.option1 = option1;
        this.option2 = option2;
        // console.log(this.option1)
        this.initDataSource = res.data.detailVO;
        // table数据处理
        this.activeName = 'first'
        this.ProcessData()
        // console.log(orgList)
      }
    },
    ProcessData(){
      let Key = this.radio1,activeName = this.activeName;
      let list1 = [],list2=[],tableObj={},allObj={};
      let tablelist=[{title: '销售小组',dataIndex: 'orgName'},{title: '销售顾问',dataIndex: 'consultantName'},{title: '潜客总数',dataIndex: 'total'}];
      // 1.提出当前来源级别的数据
      this.initDataSource.map(x=>{
        if (x[Key]) {
          list1.push(x)
        }
      })
      console.log('当前来源级别的数据',list1)
      // 提取title
      list1.map(x=>{
        let dataIndex = 'title'+x[Key]
        if (!tableObj[dataIndex]) {
          switch (Key) {
            case 'clueIdLevelOne':
              tableObj[dataIndex] = x.clueNameLevelOne
              allObj[dataIndex] = x.clueNameLevelOne
              break;
            case 'clueIdLevelTwo':
              tableObj[dataIndex] = x.clueNameLevelTwo
              allObj[dataIndex] = x.clueNameLevelTwo
              break;
            case 'clueIdLevelThree':
              tableObj[dataIndex] = x.clueNameLevelThree
              allObj[dataIndex] = x.clueNameLevelThree
              break;
            case 'clueIdLevelFour':
              tableObj[dataIndex] = x.clueNameLevelFour
              allObj[dataIndex] = x.clueNameLevelFour
              break;
            default:
              break;
          }
        }
      })
      console.log('提取title',tableObj)
      if (activeName === 'first') {
        Object.keys(tableObj).forEach(key => {
          tablelist.push({
            title: tableObj[key],
            dataIndex: key
          })
        });
        console.log('columns',tablelist)
        this.columns = tablelist;
        // 2.合并相同顾问的数据
        list2 = arrayObjDeWeight(list1,'consultant');//先获得去重的数组
        list2.forEach(x=>{
          Object.keys(tableObj).forEach(name => {
            if (activeName === 'first') {
              x[name] = 0
              list1.map(y=>{
                let yname = 'title'+y[Key];
                if (x.consultant === y.consultant && name === yname) {
                  x[name] += y.totalSource
                }
              })
            }
          })
        })
        list2 = sortRule(list2, 'orgId');
        if (list2.length > 1) {
          let tablelist2 = [...tablelist]
          // tablelist2.push({title: '全部',dataIndex: 'total'})
          let all = computedAll(tablelist2, list2);
          all['orgId'] = 'all';
          all['consultant'] = 'all';
          all['orgName'] = '全部';
          all['consultantName'] = '全部';
          list2.unshift(all);
        }
      }else if (activeName === 'second') {
        // list2.splice(0, 1)
        list2 = this.dataSource
        list2.forEach(x=>{
          Object.keys(allObj).forEach(key => {
            x[key] = GetPercent(x[key],x.total)
          });
        })
      }
      console.log(list2)
      this.dataSource = list2


    },
    async getOrgTeam() {
      const res = await getOrgTeam();
      if (res.resultCode === 200) {
        this.topFilterList.find(item => item.fieldName === 'orgId').itemList = res.data.map(x => ({ value: x.orgId, text: x.orgName }));
      }
    },
    async getUserByOrgId(val) {
      const res = await getUserByOrgId({ orgId: val });
      if (res.resultCode === 200) {
        this.topFilterList.find(item => item.fieldName === 'consultants').itemList = res.data.map(x => ({ value: x.userId, text: x.userName }));
        this.topFilterList.find(item => item.fieldName === 'consultants').initialValue = '';
      }
    },
    changeHandle(val) {
      console.log(val)
      if (val.datetime) {
        switch (val.dateType) {
          case 'day':
            val.startDate = val.datetime;
            val.endDate = val.datetime;
            break;
          case 'week':
            var weekOfday = moment(val.datetime, 'YYYY-MM-DD').format('E'); //计算指定日期是这周第几天
            var last_monday = moment(val.datetime).subtract(weekOfday-1, 'days').format('YYYY-MM-DD');//周一日期
            var last_sunday = moment(val.datetime).add(7-weekOfday, 'days').format('YYYY-MM-DD');//周日日期
            // console.log(last_monday,last_sunday)
            val.startDate = last_monday;
            val.endDate = last_sunday;
            break;
          case 'month':
            var start_monthday = moment(val.datetime)
              .startOf('month')
              .format('YYYY-MM-DD'); //月初日期
            var last_monthday = moment(val.datetime)
              .endOf('month')
              .format('YYYY-MM-DD'); //月末日期
            // console.log(start_monthday,last_monthday)
            val.startDate = start_monthday;
            val.endDate = last_monthday;
            break;
          case 'quarter':
            val.startDate = this.quarterTime[0].split(' ')[0];
            val.endDate = this.quarterTime[1].split(' ')[0];
            // console.log(val.startDate,val.endDate)
            break;
          case 'year':
            var start_yearday = moment(val.datetime)
              .startOf('year')
              .format('YYYY-MM-DD'); //年初日期
            var last_yearday = moment(val.datetime)
              .endOf('year')
              .format('YYYY-MM-DD'); //年末日期
            // console.log(start_yearday,last_yearday)
            val.startDate = start_yearday;
            val.endDate = last_yearday;
            break;
          case 'date':
            val.startDate = val.datetime[0] ? val.datetime[0]:undefined;
            val.endDate = val.datetime[1] ? val.datetime[1]:undefined;
            break;
          default:
            break;
        }
      }
      if (val.consultants.length > 0) {
        val.consultant = getTextByJs(val.consultants);
      }
      this.fetchParams = Object.assign({}, val);
      this.queryNewPotentialCount()
    },
    handleClick(tab, event) {
      // console.log(tab, event);
      this.ProcessData()
    },
    changeClue(val){
      console.log(val)
      this.activeName = 'first'
      this.ProcessData()
    },
    collapseHandle() {
      // this.$nextTick(() => {
      //   this.BaseTable.EXECUTE_RESET_HEIGHT();
      // });
    },
    closeHandler(val, type) {
      this.visible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    // 修改日期组件
    changeTemplateType(val){
      switch (val) {
        case 'day':
          this.topFilterList.find(item=>item.fieldName==='datetime').type = 'DATE';
          this.topFilterList.find(item=>item.fieldName==='datetime').dateType = 'exactdate';
          this.topFilterList.find(item=>item.fieldName==='datetime').initialValue = '';
          break;
        case 'week':
          console.log('week')
          this.topFilterList.find(item=>item.fieldName==='datetime').type = 'DATE';
          this.topFilterList.find(item=>item.fieldName==='datetime').dateType = 'week';
          this.topFilterList.find(item=>item.fieldName==='datetime').firstDayOfWeek = 1;
          this.topFilterList.find(item=>item.fieldName==='datetime').initialValue = '';
          break;
        case 'month':
          this.topFilterList.find(item=>item.fieldName==='datetime').type = 'DATE';
          this.topFilterList.find(item=>item.fieldName==='datetime').dateType = 'month';
          this.topFilterList.find(item=>item.fieldName==='datetime').initialValue = '';
          break;
        case 'quarter':
          this.topFilterList.find(item=>item.fieldName==='datetime').type = 'DATE';
          this.topFilterList.find(item=>item.fieldName==='datetime').dateType = 'quarter';
          this.topFilterList.find(item=>item.fieldName==='datetime').initialValue = '';
          break;
        case 'year':
          this.topFilterList.find(item=>item.fieldName==='datetime').type = 'DATE';
          this.topFilterList.find(item=>item.fieldName==='datetime').dateType = 'year';
          this.topFilterList.find(item=>item.fieldName==='datetime').initialValue = '';
          break;
        case 'date':
          this.topFilterList.find(item=>item.fieldName==='datetime').type = 'RANGE_DATE';
          this.topFilterList.find(item=>item.fieldName==='datetime').dateType = 'exactdaterange';
          this.topFilterList.find(item=>item.fieldName==='datetime').initialValue = '';
          break;
        default:
          this.topFilterList.find(item => item.fieldName === 'datetime').type = 'DATE';
          this.topFilterList.find(item => item.fieldName === 'datetime').dateType = 'exactdate';
          this.topFilterList.find(item => item.fieldName === 'datetime').initialValue = '';
          break;
      }
    },
  },
  mounted() {
    // this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  created() {
    this.getOrgTeam()
    this.queryNewPotentialCount()
  }
};
</script>

<style lang="less" scoped>
.Chartf{
  // margin:12px 0;
  width:49.6%;
  background:#fff;
  // max-height: 400px;
  .ChartTop{
    font-size: 16px;
    font-weight: 600;
    line-height: 58px;
    padding-left:32px;
    border-bottom: 1px solid rgba(0,4,10,0.08);
  }
}


.maintop{
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;
  overflow: hidden;
  background:#FFF;
  padding-left: 12px;
  padding-right: 12px;
  border-bottom: 1px solid rgba(0,4,10,0.08);
  .lazyLoadTab {
    /deep/ .el-tabs__header,.is-top{
      margin-bottom: 0;
    }
    /deep/ .el-tabs__active-bar{
      height: 4px;
    }
    /deep/ .el-tabs__nav-wrap::after{
      height: 0;
    }
  }
}

.tabShow{
  min-height: 300px;
}
</style>
